package com.fengmi.pay.websocket;

import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Scanner;
import java.util.concurrent.ConcurrentHashMap;

/**
 * <p>title: com.wfx</p>
 * author zhuximing
 * description:
 */
@Component
@ServerEndpoint("/order/{ordersn}")
public class WebsocketServer {


    private static ConcurrentHashMap<String,Session> sessions = new ConcurrentHashMap<>();


    //与客户端建立连接后的成功回调方法
    @OnOpen
    public void onOpen(@PathParam("ordersn")String ordersn,Session session){

        System.out.println("与client成功建立websocket连接");

        sessions.put(ordersn,session);

    }

    //当客户端发送message，回调该方法
//    @OnMessage
//    public void onMessage(String message,Session session) throws Exception{
//        System.out.println(message);
//        Scanner sc = new Scanner(System.in);
//        String msg = sc.nextLine();
//        //给客户端回话
//        session.getBasicRemote().sendText(msg);
//    }

    @OnClose
    public void onClose(Session session,@PathParam("ordersn") String ordersn){
        System.out.println("与客户端关闭了连接 bye bye");
        sessions.remove(ordersn);

    }


    public static void  sendMsgToClient(String ordersn,String msg){

        try {
            sessions.get(ordersn).getBasicRemote().sendText(msg);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}